﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Honestysoft.Financing.Model;
using System.IO;
using Honestysoft.Baseframework.Model;
using Honestysoft.BaseObject;
using System.Data;
using Honestysoft.Baseframework.WebUI;
using System.Web.SessionState;

namespace Honestysoft.Financing.WebUI.Module.Attach.Json
{
    /// <summary>
    /// MutilUploadDocument 的摘要说明
    /// </summary>
    public class MutilUploadDocument : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            //上传合同资料，根据文件名称的编码规则（如：2-C002-V001.pdf）来确定合同，项目
            context.Response.ContentType = "text/plain";
            string uploadpath = "";
            HttpPostedFile file = context.Request.Files["FileData"];
            string extName = file.FileName.Substring(file.FileName.LastIndexOf(".") + 1);
            string fileName = file.FileName.Substring(0, file.FileName.LastIndexOf("."));
            try
            {                
                //2-C002-V001
                string[] arr = fileName.Split('-');
                if (arr == null || arr.Length != 3)
                {
                    context.Response.Write("文件名：["+file.FileName+"]不符合[项目编号-合同号-申请次序]的规则；");
                    return;
                }
                DataTable dtProject = new Honestysoft.Financing.BusinessLogic.Project("").GetProjectBySN(arr[0]);
                if (dtProject == null || dtProject.Rows.Count != 1)
                {
                    context.Response.Write("无法查找到文件名：[" + file.FileName + "]对应的项目；");
                    return;
                }
                string contractCode = dtProject.Rows[0]["FCode"].ToString() + "-" + arr[1];
                QueryParameters query = new QueryParameters();
                query.Add("Code", contractCode, QueryParameters.OperatorType.Equal);
                DataTable dtContract = new BaseBusinessLogic<BD_Contract>().GetTable(query);
                if (dtContract == null || dtContract.Rows.Count != 1)
                {
                    context.Response.Write("无法查找到文件名：[" + file.FileName + "]对应的合同；");
                    return;
                }
                uploadpath = "Document/" + dtProject.Rows[0]["SN"].ToString() + dtProject.Rows[0]["Name"].ToString() + "/合同资料/" + dtProject.Rows[0]["SN"].ToString() + "-" + dtContract.Rows[0]["Code"].ToString().Substring(dtContract.Rows[0]["Code"].ToString().IndexOf("-") + 1);
                if (!Directory.Exists(context.Server.MapPath("~/" + uploadpath)))
                {
                    Directory.CreateDirectory(context.Server.MapPath("~/" + uploadpath));
                }
                if (File.Exists(context.Server.MapPath("~/" + uploadpath + "/" + fileName + "." + extName)))
                {
                    File.Delete(context.Server.MapPath("~/" + uploadpath + "/" + fileName + "." + extName));
                }
                file.SaveAs(context.Server.MapPath("~/" + uploadpath + "/" + fileName + "." + extName));
                query = new QueryParameters();
                query.Add("DataID", dtContract.Rows[0]["ID"].ToString(), QueryParameters.OperatorType.Equal);
                query.Add("AttachmentBuType", ((int)Honestysoft.Financing.Model.EnumItem.AttachmentBuType.ContractDocument).ToString(), QueryParameters.OperatorType.Equal);
                query.Add("FileName", fileName, QueryParameters.OperatorType.Equal);
                query.Add("Extension", extName, QueryParameters.OperatorType.Equal);
                BaseBusinessLogic<Sys_Attachment> bll = new BaseBusinessLogic<Sys_Attachment>(Globals.CurrentConnStringName);
                List<Sys_Attachment> lsAtt = bll.GetEntitys(query);
                Sys_Attachment obj = null;
                if (lsAtt == null || lsAtt.Count == 0)//没有附件
                {
                    obj = new Sys_Attachment();
                    obj.AttachmentBuType = ((int)Honestysoft.Financing.Model.EnumItem.AttachmentBuType.ContractDocument).ToString();
                    obj.CreateTime = DateTime.Now;
                    obj.Creator = UserLoginer.LoginUser.ID;
                    obj.DataID = dtContract.Rows[0]["ID"].ToString();
                    obj.ID = Honestysoft.BaseLibrary.Common.Guid.GetGuid();
                    obj.StoreType = ((int)Honestysoft.Baseframework.Model.EnumItem.StoreType.Disk).ToString();
                }
                else
                {
                    obj = lsAtt[0];
                }
                obj.Extension = extName;
                obj.Size = file.ContentLength;
                obj.FileName = fileName;
                obj.Path = uploadpath;
                if (lsAtt == null || lsAtt.Count == 0)//没有附件
                {
                    bll.CreateEntity(obj);
                }
                else
                {
                    bll.UpdateEntity(obj);
                }
                context.Response.Write("1");
            }
            catch(Exception ex)
            {
                context.Response.Write(ex.Message);
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}